using System;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

public class ChooseEntity : MonoBehaviour
{

    public bool IsOn
    {
        get;
        private set;
    }
    public Button ChooseButton;
    public GameObject ChooseObject;
    public UnityEvent<int> OnSelectEvent;

    private Action<int> ActiveCallback;
    
    public int ChooseID
    {
        get;
        private set;
    }

    public void InitChoose(int id, Action<int> rActiveCallback)
    {
        ChooseID = id;
        this.OnInit();
        ActiveCallback = rActiveCallback;
        this.ChangeState(false);
    }

    protected virtual void OnInit()
    {
        this.ChooseButton?.onClick.RemoveAllListeners();
        this.ChooseButton?.onClick.AddListener(this.OnSelectClick);
    }

    protected virtual void OnChangeState(bool isOn)
    {
        if (this.ChooseObject)
        {
            this.ChooseObject.SetActive(isOn);
        }
    }

    public void ChangeState(bool isOn)
    {
        if (isOn)
        {
            this.OnSelectEvent?.Invoke(ChooseID);
        }
        IsOn = isOn;
        this.OnChangeState(isOn);
    }

    /// <summary>
    /// 当该item被点击时，尝试选中当前item
    /// </summary>
    protected void OnSelectClick()
    {
        if (this.OnClickHook())
        {
            this.ActiveCallback?.Invoke(ChooseID);
        }
    }

    /// <summary>
    /// 当该Item被点击时，Hook方法，用于增加自定义条件，如果返回true点击后会被选中
    /// </summary>
    /// <returns></returns>
    protected virtual bool OnClickHook()
    {
        return true;
    }

}